<template>
    <h3>天气情况管理</h3>
    <!-- 表单 -->
    <div class="test-form">
        <div class="opt">
            <!-- 下拉菜单 -->
            <span class="label">天气情况:</span>
            <el-select @change="chooseCategoryFn" v-model="form.id" style="width: 360px" placeholder="请输入天气情况"
                size="large">
                <el-option v-for="item in categories" :label="item.text" :value="item.id" />
            </el-select>
        </div>
        <div class="opt">
            <span class="label">日期:</span>
            <el-input v-model="form.time" style="width: 360px" placeholder="请输入时间" size="large" />
        </div>
        <div class="opt">
            <span class="label">天气图标:</span>
            <!-- 上传文件组件 -->
            <el-upload v-model="form.total" class="avatar-uploader" drag action="#" :on-change="chooseImageFn"
                :auto-upload="false" :show-file-list="false">
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                </el-icon>
            </el-upload>
            <div v-if="imageUrl" style="width: 178px; text-align: center; margin-top: 5px">
                <el-button @click="photoDeleteFn(imageUrl)" type="danger" plain>删除图片</el-button>
            </div>
        </div>


        <div class="opt">
            <span class="label">最高温:</span>
            <el-input v-model="form.passline" style="width: 360px" placeholder="请输入最高温度" size="large" />
        </div>
        <div class="opt">
            <span class="label">最低温:</span>
            <el-input v-model="form.id" style="width: 360px" placeholder="请输入最低温度" size="large" />
        </div>
        <div class="opt">
            <span class="label">风向:</span>
            <el-input v-model="form.name" style="width: 360px" placeholder="请输入风向" size="large" />
        </div>
        <div class="opt">
            <span class="label">风向级别:</span>
            <el-input v-model="form.num" style="width: 360px" placeholder="请输入风向级别" size="large" />
        </div>

        <div class="opt">
            <span class="label">空气质量:</span>
            <!-- disabled -->
            <el-input v-model="form.score" style="width: 360px" placeholder="请输入空气质量" size="large" />
        </div>
        <div class="opt">
            <span class="label">周:</span>
            <!-- disabled -->
            <el-input v-model="form.riqi" style="width: 360px" placeholder="请输入周" size="large" />
        </div>
        <div class="opt">
            <el-button @click="submitTestPaperFn" type="primary" size="large">提交</el-button>
            <el-button @click="resetTestPaperFn" type="warning" plain size="large">重置</el-button>
        </div>
    </div>
    <!-- 表格 -->
    <div class="category-table">
        <el-table :data="tableData" stripe style="width: 100%">
            <el-table-column prop="index" label="序号" width="80" />
            <el-table-column prop="time" label="日期" width="150" />
            <el-table-column prop="text" label="天气情况" width="150" />
            <!-- <el-table-column prop="total" label="天气图标" width="150" /> -->

            <el-table-column label="天气图标"  width="150">
                <template #default="scope">
                    <!-- scope.row.name -->
                    <img style="width: 60px;"  :src="scope.row.total" alt="">
                </template>
            </el-table-column>

            <el-table-column prop="passline" label="最高温" width="150" />
            <el-table-column prop="id" label="最低温" width="150" />
            <el-table-column prop="name" label="风向" width="150" />
            <el-table-column prop="num" label="级别" width="150" />
            <el-table-column prop="score" label="空气质量" width="150" />
            <el-table-column prop="riqi" label="周" width="150" />

            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import { photoUpload, photoDelete, categoryAdd, categoryList, categoryRemove, examAdd, examList, examRemove } from '../../api/request'
import type { Action } from 'element-plus'
import api from '../../api/index'
const input = ref('')
const imageUrl = ref('')
const pic = ref('')
const tip=api.url
// 表格数据
const tableData = ref<any>([])
// 选择图标
const chooseImageFn = async (file: any) => {
    if (file) {
        // 创建表单实例
        let fd = new FormData()
        fd.append('photo', file.raw)
        // 调用上传图片的方法
        await photoUpload(fd)
            .then(
                content => {
                    console.log(content)
                    let { code, picUrl } = content;
                    if (code == 200) {
                        // 赋值（响应式）
                        imageUrl.value = api.url + picUrl;
                        pic.value = picUrl;
                        form.total=pic.value;
                        console.log(imageUrl.value)
                    }
                    else {
                        ElMessage.error(content.msg);
                    }
                }
            )
    }

}
// 删除图片
const photoDeleteFn = async (picUrl: string) => {
    await photoDelete({ picUrl })
        .then(
            content => {
                // console.log(content);
                let { code } = content;
                if (code == 200) {
                    // 重置图片路径
                    imageUrl.value = "";
                }
            }
        )
}

interface RuleForm {
    id: string
    time: string
    name: string
    total: string
    passline: number | string
    text: string
    eid?: string
    num: number | string
    score: string
    riqi: string

}
const categories = ref<any>([])

const form = reactive<RuleForm>({
    id: "",
    time: "",
    name: "",
    total: "",
    passline: "",
    text: "",
    num: "",
    score: "",
    riqi: "",

})

// 侦听器
// watch(form, (newForm: any) => {
//     if (newForm.total && newForm.num) {
//         form.score = newForm.total / newForm.num
//     }
// })

// 点击重置
const resetTestPaperFn = () => {
    form.id = ""
    form.time = ""
    form.name = ""
    form.total = ""
    form.passline = ""
    form.text = ""
    form.num = 0
    form.score = ""
    form.riqi ="" ;
}

// 点击提交
const submitTestPaperFn = async () => {
    // 获取表单信息
    let { id, time,text , total, passline, name, num, score,riqi} = form;
    console.log(id, time,text , total, passline, name, num, score,riqi)
    // 判断是否有值
    if (id && time && text && total && passline && name && num &&  score && riqi) {
        await examAdd({ id, time,text, total,passline, name, num, score,riqi })
            .then(
                content => {
                    // console.log(content)
                    let { code, msg } = content;
                    if (code == 200) {
                        examListFn();
                        // 重置表单信息
                        resetTestPaperFn();
                        ElMessage.success(msg)
                    }
                    else {
                        ElMessage.error(msg)
                    }
                },
                err => {
                    console.log(err)
                }
            )
    }
    else {
        ElMessage.error("缺少参数，请检查在提交")
    }
}


// 获取试卷列表
const examListFn = async () => {
    await examList()
        .then(
            content => {
           
                let { code, msg, result } = content;
                if (code == 200) {
                    let arr = result.map((item: any, i: number) => {
                        item.index = i + 1;
                        item.total = api.url + item.total
                        return item
                    })
                    tableData.value = arr;
                    console.log('111',tableData.value);
                }
                else {
                    ElMessage.error(msg)
                }
            }
        )
}

// 监听下拉菜单
const chooseCategoryFn = () => {
    let arr = categories.value.filter((item: any) => item.id == form.id)
    if (arr.length == 1) {
        form.text = arr[0].text;
    }
    console.log(form.id);
    console.log(form.text);
}

// 获取分类列表
const getCategoryListFn = async () => {
    await categoryList()
        .then(
            content => {
                // console.log(content)
                let { code, result } = content;
                if (code == 200) {
                    categories.value = result;
                }
            }
        )
}

// 点击删除
const handleDelete = (index: number, row: any) => {
    // console.log(index, row)
    // console.log(index, row)
    // 获取当前点击的选项
    let { eid, time } = row;
    ElMessageBox.confirm(
        `是否删除这个“${time}”时间?`,
        '提示',
        {
            distinguishCancelAndClose: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        }
    )
        .then(async () => {
            // console.log("点击确定")
            // 删除考试分类
            await examRemove({ eid })
                .then(
                    content => {
                        let { code, msg } = content;
                        if (code != 200) {
                            ElMessage.error(msg)
                        }
                    }
                )
            // 删除程序中数组对应的数据
            tableData.value.splice(index, 1);
        })
        .catch(() => {
            // console.log("点击取消")
        })
}

// 初始化数据
getCategoryListFn();
examListFn();


</script>

<style lang="scss">
.test-form {
    .opt {
        margin-top: 15px;

        .avatar-uploader {
            margin-left: 150px;
            margin-top: -20px;
            width: 200px;
        }

        .label {
            width: 150px;
            display: inline-block;
            text-align: right;
            padding: 0 10px;
        }
    }
}

.category-table {
    margin-top: 15px;
}
</style>